package com.cdtu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdtu.entity.Admin;
import com.cdtu.entity.Messages;
import com.cdtu.entity.User;
import com.cdtu.service.AdminService;
import com.cdtu.service.MessagesService;
import com.cdtu.service.UserService;
import com.cdtu.vo.MessageVo;
import com.cdtu.vo.R;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/message")
public class MessageController {

    public static String CACHE_CERTIFY_KEY="message:certify:";
    @Autowired
    MessagesService messagesService;
    @Autowired
    AdminService adminService;
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;
    /**
    *  获取管理员申请列表
    * @author wp
    * @param
    * @date 2023/2/1 11:16
    * @return
    */
    @GetMapping("/management")
    public R  getManagementApplicationMessageList(){
          List<MessageVo> adminsList=new ArrayList<>();
        LambdaQueryWrapper<Messages> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Messages::getState,0);
              queryWrapper.eq(Messages::getType,0);
        List<Messages> list = messagesService.list(queryWrapper);
        if (list.size()>0){
            for (Messages messages : list) {
                MessageVo messageVo = new MessageVo();
                messageVo.setMessages(messages);
                Admin admin = adminService.getById(messages.getIdKey());
                if (admin!=null) {
                    messageVo.setName(admin.getName());
                }
                adminsList.add(messageVo);
            }
        }
        return R.success(adminsList);
    }

    /**
    * 用户反馈信息
    * @author wp
    * @param
    * @date 2023/2/1 16:47
    * @return
    */
    @GetMapping("/userFeedback")
    public R  getUserFeedbackMessageList(){
        List<MessageVo> userFeedbackList=new ArrayList<>();
        LambdaQueryWrapper<Messages> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Messages::getState,0);
        queryWrapper.eq(Messages::getType,2);
        List<Messages> list = messagesService.list(queryWrapper);
        for (Messages messages : list) {
            MessageVo messageVo = new MessageVo();
            messageVo.setMessages(messages);
            messageVo.setName(userService.getById(messages.getIdKey()).getName());
            userFeedbackList.add(messageVo);
        }
        return R.success(userFeedbackList);
    }
    /**
    *  信息查看改变状态
    * @author wp
    * @param
    * @date 2023/2/1 16:18
    * @return
    */
    @PutMapping("/marking/{id}")
    public R updateMessageState(@PathVariable("id") long id){
        LambdaQueryWrapper<Messages> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Messages::getId,id);
        Messages message = messagesService.getOne(queryWrapper);
        message.setState(1);
        boolean isTrue = messagesService.updateById(message);
        if (isTrue){
            return R.success("批阅成功");
        }
        else
            return R.error("批阅失败");
    }

    @GetMapping("/certify")
    public R getMessageList(){
        LambdaQueryWrapper<Messages> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Messages::getType,1);
        queryWrapper.eq(Messages::getState,0);
        List<Messages> list = messagesService.list(queryWrapper);
        List<MessageVo> voList=new ArrayList<>();
        for (Messages messages : list) {
            MessageVo vo=new MessageVo();
            Long uid = messages.getIdKey();
            User user = userService.getById(uid);
//            vo.setName(user.getName());
            vo.setMessages(messages);
            voList.add(vo);
        }
        return R.success(voList);
    }

    @GetMapping("/UCertify/{uid}")
    public R certifyMessageDetail(@PathVariable("uid") long uid){
        String cacheJson = redisTemplate.opsForValue().get(CACHE_CERTIFY_KEY + uid);


        return R.success(cacheJson);
    }

    @Transactional
    @PutMapping("/reject/{uid}/{mid}/{aid}")
    public R rejectCertifyMessage(@PathVariable("uid") long uid,
                                  @PathVariable("mid") long mid,
                                  @PathVariable("aid") long aid,
                                  @RequestParam("advise") String advise){
//        System.out.println(uid);
//        System.out.println(mid);
//        System.out.println(aid);
//        System.out.println(advise);
        Messages messages = messagesService.getById(mid);
        messages.setState(2);
        boolean result = messagesService.updateById(messages);

        if (!result){
            return R.error("处理失败，请稍后再尝试");
        }

        Messages toUser = new Messages();
        toUser.setIdKey(uid);
        toUser.setTime(new Date());
        toUser.setDescription(advise);
        toUser.setType(3);
        toUser.setState(0);

        result = messagesService.save(toUser);
        if (!result){
            return R.error("处理失败，请稍后再尝试");
        }
//        redisTemplate.delete(CACHE_CERTIFY_KEY+uid);
        return R.success("处理成功");
    }

    @GetMapping("/userMsg/{pageNow}/{uid}")
    public R getUserMsgList(@PathVariable("pageNow") Integer pageNow,
                            @PathVariable("uid") long uid){
//        System.out.println("收到请求");
        Page<Messages> page =new Page<>(pageNow,10);
        LambdaQueryWrapper<Messages> queryWrapper=new LambdaQueryWrapper<>();

        queryWrapper.eq(Messages::getIdKey,uid);
        queryWrapper.and(wq->wq.eq(Messages::getType,3).or()
                .eq(Messages::getType,5)
        );
        queryWrapper.orderByDesc(Messages::getTime);
        Page<Messages> messagesPage = messagesService.page(page, queryWrapper);

        List<Messages> list = messagesService.list();
        long count = list.stream()
                .filter(messages -> messages.getType()==3 || messages.getType()==5)
                .filter(messages -> messages.getIdKey()==uid)
                .filter(messages -> messages.getState() == 0).count();
        messagesPage.setTotal(count);
        return R.success(messagesPage);
    }

    @PutMapping("/modState/{mid}")
    public R changeMsgState(@PathVariable("mid") long mid){
//        System.out.println("mid是"+mid);
        LambdaQueryWrapper<Messages> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(Messages::getId,mid);

        Messages byId = messagesService.getById(mid);
        byId.setState(1);
//        System.out.println("byId是"+byId);
        boolean result = messagesService.updateById(byId);
        return R.success(byId);
    }

    @GetMapping("/emeMsg")
    public R emeMsg(){
        System.out.println("mid是");
        LambdaQueryWrapper<Messages> queryWrapper=new LambdaQueryWrapper();
        //4表示紧急救援消息
        queryWrapper.eq(Messages::getType,4);
        List<Messages> list = messagesService.list(queryWrapper);
        List<Messages> messagesList = list.stream().filter(messages -> messages.getState() == 0)
                .collect(Collectors.toList());
        return R.success(messagesList);
    }
}
